package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.domain.ArticleTag;
import org.example.domain.Tag;
import org.example.mapper.ArticleTagMapper;
import org.example.mapper.TagMapper;
import org.example.param.TagAddParam;
import org.example.param.TagDeleteParam;
import org.example.param.TagFuzzyParam;
import org.example.param.TagUpdateParam;
import org.example.service.TagService;
import org.example.utils.HttpCode;
import org.example.utils.Result;
import org.example.vo.TagVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TagServiceImpl implements TagService {

    @Resource
    private TagMapper tagMapper;
    @Resource
    private ArticleTagMapper articleTagMapper;

    @Override
    public Result all() {
        return Result.success(tagMapper.selectList(null));
    }

    /**
     * 添加前判断是否有相同名称的标签
     * @param tagAddParam
     * @return
     */
    @Override
    public Result add(TagAddParam tagAddParam) {
        Object data = findTagByName(tagAddParam.getTagName().trim()).getData();
        if (data != null){
            return Result.fail(HttpCode.TAG_EXIST);
        }
        Tag tag = Tag.builder()
                .tagName(tagAddParam.getTagName().trim())
                .avatar(tagAddParam.getAvatar())
                .createDate(System.currentTimeMillis())
                .isDelete(0).build();
        int total = tagMapper.insert(tag);
        if (total == 0){
            return Result.fail(HttpCode.INSERT_ERROR);
        }
        return Result.success();
    }

    @Override
    public Result findTagByName(String tagName) {
        if (!StringUtils.hasText(tagName)){
            return Result.fail(HttpCode.PARAM_ERROR);
        }
        LambdaQueryWrapper<Tag> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Tag::getTagName,tagName);
        wrapper.last("limit 1");
        Tag tag = tagMapper.selectOne(wrapper);
        return Result.success(tag);
    }

    @Override
    public Result delete(TagDeleteParam tagDeleteParam) {
        if (tagDeleteParam.getId() == null && !StringUtils.hasText(tagDeleteParam.getTagName())){
            return Result.fail(HttpCode.PARAM_ERROR);
        }
        LambdaQueryWrapper<Tag> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(tagDeleteParam.getId()!= null ,Tag::getId,tagDeleteParam.getId());
        wrapper.eq(tagDeleteParam.getTagName()!=null,Tag::getTagName,tagDeleteParam.getTagName());
        int total = tagMapper.delete(wrapper);
        if (total == 0){
            return Result.fail(HttpCode.DELETE_ERROR);
        }
        return Result.success();
    }

    /**
     * 更新前,检查是否已存在此标签名称
     * @param tagUpdateParam
     * @return
     */
    @Override
    public Result update(TagUpdateParam tagUpdateParam) {
        Tag data = (Tag) findTagByName(tagUpdateParam.getTagName().trim()).getData();
        // 这个Long的比较使用longValue(),long类型缓存是-128~127,超过范围比较的是引用地址
        if (data != null && data.getId().longValue() != tagUpdateParam.getId()){
            return Result.fail(HttpCode.TAG_EXIST);
        }
        Tag tag = Tag.builder()
                .id(tagUpdateParam.getId())
                .tagName(tagUpdateParam.getTagName().trim())
                .avatar(tagUpdateParam.getAvatar())
                .build();
        int total = tagMapper.updateById(tag);
        if (total == 0){
            return Result.fail(HttpCode.UPDATE_ERROR);
        }
        return Result.success();
    }

    /**
     * 模糊查询,分页
     * @param tagFuzzyParam
     * @return
     */
    @Override
    public Result fuzzy(TagFuzzyParam tagFuzzyParam) {
        LambdaQueryWrapper<Tag> wrapper = new LambdaQueryWrapper<>();
        // 条件
        wrapper.like(StringUtils.hasText(tagFuzzyParam.getTagName()),Tag::getTagName,tagFuzzyParam.getTagName());
        wrapper.ge(tagFuzzyParam.getStartDate()!=null,Tag::getCreateDate,tagFuzzyParam.getStartDate());
        wrapper.le(tagFuzzyParam.getEndDate()!=null,Tag::getCreateDate,tagFuzzyParam.getEndDate());

        Page<Tag> tagPage = tagMapper.selectPage(new Page<>(tagFuzzyParam.getPageNum(), tagFuzzyParam.getPageSize()),
                wrapper);
        return Result.success(tagPage);
    }

    // ----------------------------------------------//
        // article_tag
    // ----------------------------------------------//


    @Override
    public int deleteArticle(Long id) {
        LambdaQueryWrapper<ArticleTag> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ArticleTag::getArticleId,id);
        int total = articleTagMapper.delete(wrapper);
        return total;
    }

    @Override
    public int addArticle(Long articleId, List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)){
            return 0;
        }

        ids.forEach( id -> {
            ArticleTag articleTag = ArticleTag.builder()
                    .articleId(articleId)
                    .tagId(id)
                    .build();
            articleTagMapper.insert(articleTag);
        });
        return 1;
    }

    @Override
    public List<Long> findArticleIdById(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)){
            return new ArrayList<>();
        }
        LambdaQueryWrapper<ArticleTag> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(ArticleTag::getArticleId);
        wrapper.in(ArticleTag::getTagId,ids);
        List<Object> articlesId = articleTagMapper.selectObjs(wrapper);
        List<Long> result = articlesId.stream()
                .map(s -> Long.valueOf(String.valueOf(s)))
                .collect(Collectors.toList());
        return result;
    }

    @Override
    public List<Tag> findTagsByArticleId(Long articleId) {
        LambdaQueryWrapper<ArticleTag> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ArticleTag::getArticleId,articleId);
        wrapper.select(ArticleTag::getTagId);
        List<Object> list = articleTagMapper.selectObjs(wrapper);
        List<Long> tagIds = list.stream().map(s -> Long.valueOf(String.valueOf(s))).collect(Collectors.toList());
        return findTagsById(tagIds);
    }

    @Override
    public Result hot(Integer limit) {
        if (limit == null || limit <= 0){
            limit = 5 ;
        }
        List<TagVo> tagVoList = tagMapper.hot(limit);
        return Result.success(tagVoList);
    }

    @Override
    public Result findTagById(Long id) {

        Tag tag = tagMapper.selectById(id);
        return Result.success(tag);
    }

    // 根据id找出对应的tag
    public List<Tag> findTagsById(List<Long> ids){
        if (CollectionUtils.isEmpty(ids)){
            return new ArrayList<>();
        }
        LambdaQueryWrapper<Tag> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Tag::getId,ids);
        List<Tag> tagList = tagMapper.selectList(wrapper);
        return tagList;
    }
}
